import * as PIXI from 'pixi.js'
import { PixiComponent } from '@inlet/react-pixi'

const drawCilcle = (r1, r2) => g => (x, y, scale) => (outerColor, innerColor) => {
  g.lineStyle(0)
  g.beginFill(outerColor, 1)
  g.drawCircle(x, y, r1 / scale)
  g.beginFill(innerColor, 1)
  g.drawCircle(x, y, r2 / scale)
  g.endFill()
}

function onDragStart(event) {
  // store a reference to the data
  // the reason for this is because of multitouch
  // we want to track the movement of this particular touch
  this.data = event.data
  this.dragging = true
  this.oldPosition = this.data.getLocalPosition(this.parent)
}

function onDragEnd() {
  this.dragging = false
  this.data = null
}

function onDragMove() {
  if (this.dragging) {
    const newPosition = this.data.getLocalPosition(this.parent)
    const delatX = newPosition.x - this.oldPosition.x
    const delatY = newPosition.y - this.oldPosition.y
    this.move(delatX, delatY)
    this.oldPosition = newPosition
  }
}

const drawCilcle83 = drawCilcle(8, 3)

export default PixiComponent('Point', {
  create: ({ move }) => {
    const g = new PIXI.Graphics()
    g.move = move
    g.interactive = true
    g.buttonMode = true
    return g
  },
  didMount: () => {},
  willUnmount: () => {},
  applyProps: (instance, oldProps, newProps) => {
    instance.clear()
    instance.removeAllListeners()
    instance
      .on('mousedown', onDragStart)
      .on('mouseup', onDragEnd)
      .on('mouseupoutside', onDragEnd)
      .on('mousemove', onDragMove)
    const {
      point, scale, outerColor, innerColor,
    } = newProps
    const x = point[0]
    const y = point[1]
    drawCilcle83(instance)(x, y, scale)(outerColor, innerColor)
  },
})
